<?php

/**
 +------------------------------------------------------------------------------
 * Cart实现类
 +------------------------------------------------------------------------------
 * @category   Think
 * @package  Think
 * @subpackage  Util
 * @author    Asun(sun2grit@sina.com)
 * @version   $Id: Cart.class.php
 +------------------------------------------------------------------------------
 */

class Cart{

	//THINKPHP_MODLE
	private $model;
	
	private $user_cart;
	private $discount=array();//array(20=>-10);
    private $uid;
	private $user_type=0;
	private $goods;
	private $cart;
	private $deliver_money=10;
	private $discount_rate=1;
	public function __construct($model,$uid,$user_type){
		$this->model = $model;
		$this->uid = $uid;
		$this->user_type=$user_type;
		$this->discount_rate=getUserDiscount($user_type);
		$this->user_cart = new Model();
		$this->cart=&$_SESSION['cart'];
		$this->goods=&$_SESSION['cart']['goods_list'];
		//unset($_SESSION['cart']);
		if(!$_SESSION['cart']){
			$this->cart = array();
			$this->cart['goods_list'] = array();
			
			$this->cart['total_num'] = 0;
			$this->cart['total_price'] = 0.00;
			$this->cart['deliver_money'] = $this->deliver_money;
		}
			//如果是已经登录的用户
			
		//如果是已经登录的用户
		
		if($this->uid and empty($this->goods)){
			//清空SESSION购物车信息
			$this->cart['total_price'] = 0;
			$this->cart['total_num'] = 0;
			$this->cart['deliver_money'] = $this->deliver_money;				
			//根据用户的购物车信息，重构SESSION中的购物车信息
			$user_cart_result = $this->user_cart->query("select cart_id,user_id,prod_id,prod_code,prod_name,prod_img,prod_price,cart_price,sizes,amount,shipping,is_spec from prod_cart where user_id = '".$this->uid."'");
			//dump("select cart_id,user_id,prod_id,prod_code,prod_name,prod_img,prod_price,cart_price,sizes,amount,shipping,is_spec from prod_cart where user_id = '".$this->uid."'");
			foreach ($user_cart_result as $value){
				
				if ($value['is_spec']==2){//仅允许买一件
					$this->clear();
					$this->cart['IsSpec']=2;
				}	
				$this->goods[$value['prod_id']] = array(
														'prod_id' => $value['prod_id'],
														'prod_code' => $value['prod_code'],
														'prod_img' => $value['prod_img'],
														'prod_name' => $value['prod_name'],
														'cart_price' => $value['cart_price'],
														'prod_price' => $value['prod_price'],
														'shipping' => $value['shipping'],
														'amount'=>$value['amount'],
														'is_spec'=>$value['is_spec'],
														'sizes' =>unserialize($value['sizes'])
													);
				$this->cart['total_price'] = floatval($this->cart['total_price']) + $value['cart_price']*$value['amount'];
				$this->cart['total_num'] = $this->cart['total_num'] + $value['amount'];		
				$this->cart['deliver_money'] = $this->cart['deliver_money']+$value['shipping'];		
				
			}
			$discount_money=0;
			$prod_count=$this->cart['total_num'];
			while($prod_count>0){
				$finded=false;
				foreach($this->discount as $c=>$m){
					if ($prod_count>$c){
						$prod_count=$prod_count-$c;
						$discount_money=$discount_money+$m;
						$finded=true;
						break;
					}
				}
				if (!$finded){
					break;
				}
			}
			$this->cart['discount_money'] = $discount_money;				
		}
	}
	public function json_return($data){
		$data['discount_money']=floatval($this->cart['discount_money']);
		$data['total_price']=floatval($this->cart['total_price']);
		$data['total_num']=intval($this->cart['total_num']);
		$data['deliver_money']=floatval($this->cart['deliver_money']);
		return json_encode($data);
	}
	//添加单个商品到购物车
	public function add_goods($goods_id,$size_code,$size_count){
	
		$goods_id = $goods_id * 1;
		$size_count=max(intval($size_count),1);
		if ($this->cart['IsSpec']==2){//仅允许买一件
			return $this->json_return(array('state' => -1,'info' =>'购物车内有单件特价商品，不允许再添加其它商品，您可以进行结算或者清空购物车再操作！'));
		}
		if($goods_id){
		    $sql="select ProdId,p.ProdCode,Cost,ImgPrev,SitePrice,Sizes,p.ProdName,
		p.brand,TrueStock,other,[state],isExtendBig,isExtendSmall,IsNull(user_price.prod_price,p.price) Price,IsNull(user_price.id,0) PriceId,IsNull(user_price.is_spec,IsSpec) is_spec,IsNull(user_price.max_count,0) max_count,
		IsNull(user_price.shipping,CASE p.Shipping WHEN -1 THEN 0 ELSE p.Shipping END) shipping from v_products p WITH(NOLOCK) left join user_price on p.ProdCode = user_price.ProdCode and (user_price.UserId='' or user_price.UserType=".$this->user_type." or user_price.UserId='".$this->uid."') and user_price.end_time>GETDATE() where p.ProdId=".$goods_id."";
			
			
			$products=$this->model->query($sql);
			
			if($products && $product=$products[0]){
				/*
				if($this->model->status = 0){
					return $this->json_return(array('state' => 2,'info' => 'This goods is down!'));
				}
				*/
				//Log::write('清空'.$product['IsSpec'], Log::SQL);
				$max_count=$product['max_count']<1?9999:$product['max_count'];
			    if ($max_count<9999){
				   $firstday = date("Y-m-01 00:00:00",time());   
				   $lastday = date("Y-m-d 23:59:59",strtotime("$firstday +1 month -1 day")); 
				   $sql="select COUNT(1) as c from ProdOrderLog where UserId='".$this->uid."' and ProdCode='".$product['ProdCode']."' and status<>-2 and (OrderTime between '$firstday' and '$lastday')";
				   $counts=$this->model->query($sql);
				   
				   Log::write('清空'.$sql, Log::SQL);
					if ($count=$counts[0] and $count['c']>=$max_count){
						return $this->json_return(array('state' => 0,'info' => '本商品本月只能购买'.$max_count.'件!'));
					}
				}
				if ($product['is_spec']==2){//仅允许买一件
					$this->clear();
					$this->cart['IsSpec']=2;
				}
				
				if ($product['is_spec']>0){
					$tmp_price=round($product['Price'],1);
				}else{
					$tmp_price=round($product['Price']*$this->discount_rate,1);//calc_price($this->model->Cost,$this->model->SitePrice,$this->model->Sizes,$this->model->LifeYear);
				}
				
				if($product['Price']>0){
					
					if(!$this->goods[$goods_id]){//风物车无此商品
						$amount=$size_count;
						$sizes=array($size_code=>$size_count);
						$goods= array(
									'prod_id' => $product['ProdId'],
									'prod_code' => $product['ProdCode'],
									'prod_name' => $product['ProdName'],
									'prod_img' => $product['ImgPrev'],
									'cart_price' => $tmp_price,
									'prod_price' => $product['SitePrice'],
									'is_spec' => $product['is_spec'],
									'shipping' => $product['shipping'],
									'amount'=>$amount,
									'sizes' => $sizes
								);
						$sizes=serialize($goods['sizes']);
						$this->goods[$goods_id]=$goods;
						$this->cart['total_price'] = floatval($this->cart['total_price']) + $tmp_price*$amount;
						$this->cart['total_num'] = intval($this->cart['total_num']) + $amount;
						$this->cart['deliver_money'] = max(0,intval($this->cart['deliver_money']) + $product['shipping']);
						
						$discount_money=0;
						$prod_count=$this->cart['total_num'];
						while($prod_count>0){
							$finded=false;
							foreach($this->discount as $c=>$m){
								if ($prod_count>$c){
									$prod_count=$prod_count-$c;
									$discount_money=$discount_money+$m;
									$finded=true;
									break;
								}
							}
							if (!$finded){
								break;
							}
						}
						$this->cart['discount_money'] = $discount_money;						
						//如果是登录用户,记录到biz_cart表中
						if($this->uid){
							$this->user_cart->execute("INSERT INTO prod_cart(user_id, session_id, prod_id, sizes, prod_code, prod_name,prod_img, prod_price, cart_price,shipping, is_spec,discount, quantity, amount, create_time) VALUES ('".$this->uid."', '".session_id()."', '".$product['ProdId']."', '".$sizes."', '".$product['ProdCode']."', '".$product['ProdName']."','".$product['ImgPrev']."', '".$product['SitePrice']."', '".$tmp_price."', '".$product['shipping']."', '".$product['is_spec']."', '0', '0', '".$amount."', '".date("Y-m-d H:i:s")."');");
							$user_cart_result = $this->user_cart->query("select top 1 cart_id,prod_id from prod_cart where user_id = '".$this->uid."'");
							if($user_cart_result[0]){
								return $this->json_return(array('state' => 1,'info' => '商品成功加入购物车!'));
							}
						}
					}else{
						$size_amount=intval($this->goods[$goods_id]['sizes'][$size_code]);
						$size_stock=getSizeAry($product['Sizes'],$product['TrueStock']);
						if ($size_amount>=$max_count){
							return $this->json_return(array('state' => 0,'info' => '此商品只能添加'.$max_count.'件!'));
						}else if (intval(find_size($size_stock,$size_code))<=$size_amount){
							return $this->json_return(array('state' => 0,'info' => '没有库存了！'));
						}else{
							$amount=intval($this->goods[$goods_id]['amount'])+$size_count;
							$this->goods[$goods_id]['amount']=$amount;
							$this->cart['total_price'] = floatval($this->cart['total_price']) + $tmp_price*$size_count;
							$this->cart['total_num'] = intval($this->cart['total_num']) + $size_count;						
							$this->cart['deliver_money'] = max(0,intval($this->cart['deliver_money']) + $product['shipping']);
							$size_amount=$size_amount+$size_count;
							$this->goods[$goods_id]['sizes'][$size_code]=$size_amount;
							$sizes=serialize($this->goods[$goods_id]['sizes']);
							if($this->uid){
								$this->user_cart->execute("update prod_cart set amount=$amount,sizes='$sizes' where user_id='{$this->uid}' and prod_id='$goods_id'");
							}
							return $this->json_return(array('state' => 1,'amount'=>$size_amount,'info' => '商品成功加入购物车!'));
						}
					}
				}
				else{
					return $this->json_return(array('state' => -1,'info' => '价格不能为０'));
				}
			}
			else{
				return $this->json_return(array('state' => -2,'info' => "没有找到此商品!"));
			}
		}
		else{
			return $this->json_return(array('state' => -3,'info' => '商品ID为空！'));
		}
	}
	
	//从购物车删除单个商品
	public function delete_goods($goods_id,$size_code){
		$goods_id = $goods_id * 1;
		if($goods_id){
			$goods=$this->goods[$goods_id];
			if($goods && $goods['sizes'][$size_code]){
				$this->cart['total_price'] = floatval($this->cart['total_price']) - $goods['cart_price']*1;
				$this->cart['total_num'] = intval($this->cart['total_num']) - 1;
				$this->cart['deliver_money'] = max(0,intval($this->cart['deliver_money']) - $goods['shipping']);
				$this->goods[$goods_id]['amount'] = intval($goods['amount']) - 1;
				
				$amount=$this->goods[$goods_id]['amount'];
				if ($amount>=0){
					$discount_money=0;
					$prod_count=$this->cart['total_num'];
					while($prod_count>0){
						$finded=false;
						foreach($this->discount as $c=>$m){
							if ($prod_count>$c){
								$prod_count=$prod_count-$c;
								$discount_money=$discount_money+$m;
								$finded=true;
								break;
							}
						}
						if (!$finded){
							break;
						}
					}
					$this->cart['discount_money'] = $discount_money;
					$size_amount=intval($this->goods[$goods_id]['sizes'][$size_code]);
					if ($size_amount>1){
						$size_amount=$size_amount-1;
						$this->goods[$goods_id]['sizes'][$size_code]=$size_amount;
					}else{
						$size_amount=0;
						unset($this->goods[$goods_id]['sizes'][$size_code]);
					}
					if ($goods['is_spec']==2){
						unset($this->cart['IsSpec']);
					}
					if ($amount<1){//产品已经清除
						unset($this->goods[$goods_id]);
						if($this->uid){
							$user_cart_result = $this->user_cart->query("select top 1 cart_id,prod_id from prod_cart where user_id = '".$this->uid."' and prod_id = $goods_id");
							if($user_cart_result[0]){
								$this->user_cart->execute("delete from prod_cart where cart_id = ".$user_cart_result[0]['cart_id']."");// limit 1
							}
						}
						return $this->json_return(array('state' => 1,'amount'=>$size_amount,'info' => '商品已经从购物车中清除!'));	
					}else{//更新
						$sizes=serialize($this->goods[$goods_id]['sizes']);
						if($this->uid){
							$this->user_cart->execute("update prod_cart set amount=$amount,sizes='$sizes' where user_id='{$this->uid}' and prod_id='$goods_id'");
						}
						return $this->json_return(array('state' => 1,'amount'=>$size_amount,'info' => '商品删除成功!'));						
					}
					
					
				} else{
					return $this->json_return(array('state' => -1,'info' => '在购物车中没有找到该商品!'));
				}
			}else{
				return $this->json_return(array('state' => -1,'info' => '在购物车中没有找到该商品!'));
			}
		}else{
			return $this->json_return(array('state' => -2,'info' => '商品ID为空！'));
		}
	}
	
	//从购物车批量删除商品
	public function delete_batch_goods($goods_id_string){
		$goods_id_arr = explode(',',$goods_id_string);
		if(sizeof($goods_id_arr)){
			foreach ($goods_id_arr as $goods_id){
				$goods_id = $goods_id * 1;
				if($this->goods[$goods_id]){
					$this->cart['total_price'] = $this->cart['total_price'] - $this->goods[$goods_id]['cart_price']*$this->goods[$goods_id]['amount'];
					$this->cart['total_num'] = $this->cart['total_num'] - $this->goods[$goods_id]['amount'];
					unset($this->goods[$goods_id]);
					//如果登录了，同时删除biz_cart中该用户的信息
					if($this->uid){
						$user_cart_result = $this->user_cart->query("select top 1 cart_id,prod_id from prod_cart where user_id ='".$this->uid."' and prod_id = $goods_id ");
						if($user_cart_result[0]){
							$this->user_cart->execute("delete from prod_cart where cart_id = ".$user_cart_result[0]['cart_id']."");
						}
					}
				}
			}
			$discount_money=0;
			$prod_count=$this->cart['total_num'];
			while($prod_count>0){
				$finded=false;
				foreach($this->discount as $c=>$m){
					if ($prod_count>$c){
						$prod_count=$prod_count-$c;
						$discount_money=$discount_money+$m;
						$finded=true;
						break;
					}
				}
				if (!$finded){
					break;
				}
			}
			$this->cart['discount_money'] = $discount_money;			
			return $this->json_return(array('state' => 1,'info' => '商品批量删除成功!'));
		}
		else{
			return $this->json_return(array('state' => -1,'info' => '参数错误!'));
		}
	}
	
	//清空购物车
	public function clear(){
		unset($_SESSION['cart']);
		$this->cart=&$_SESSION['cart'];
		$this->goods=&$_SESSION['cart']['goods_list'];		
		$this->cart['goods_list'] = array();
		$this->cart['total_num'] = 0;
		$this->cart['total_price'] = 0.00;
		$this->cart['deliver_money'] = $this->deliver_money;

	}
	public function empty_cart(){
		$this->clear();
		if($this->uid){
			$this->user_cart->execute("delete from prod_cart where user_id = '".$this->uid."'");
		}			
		return $this->json_return(array('state' => 1,'info' => '清空购物车成功!'));
	}
	public function get_deliver_money(){
		return $this->cart['deliver_money'];
	}	
	//输出购物车信息
	public function return_cart_info(){
		return $this->cart;
	}
	public function get_goods_array(){
		//货号|价格|状态|尺寸
		$goods_list=array();
		foreach($this->goods as $goods){
			foreach($goods[sizes] as $size=>$amout){
				for ($i = 1; $i <=$amout; $i++) {
					
					$prod['code']=$goods['prod_code'];
					$prod['price']=$goods['cart_price'];
					$prod['size']=$size;
					$prod['state']=0;
					$goods_list[]=$prod;
				}
			}
		}
		return $goods_list;
		
	}
}

 ?>